import asyncio
import aiohttp
import os

env = 'prod'
prod_env = "https://app.weiquanpro.com"
test_env = "http://119.91.232.205:6666"

if env == 'prod':
    env = prod_env
elif env == 'test':
    env = test_env
else:
    env = test_env

# 上传文件的接口
upload_url = f"{env}/v1/loss_caculation/create_caclulation_excel"
# 开始测算的接口
calculate_url_template = f"{env}/v1/loss_caculation/begin_caculat?caculateId={{}}"

# 上传请求头
upload_headers = {
    "platform": "ios",
    "appversion": "1.0.0",
    "language": "zh-CN",
    # 测试环境
    # "Authorization": "Bearer eyJhbGciOiJIUzI1NiJ9.eyJqdGkiOiI4OTI5Njk4NzU4MzA0NzY4MDAiLCJzdWIiOiJvYTF2dzY5NzVjbEZ6cHBZZXEzZFFXaUwyLXRjIiwiaWF0IjoxNzM3MTkxNzUwLCJleHAiOjIzNDE5OTE3NTAsImNvbW1vbkhlYWRlclBhcmFtcyI6eyJwbGF0Zm9ybSI6IiIsImFwcFZlcnNpb24iOiIiLCJsYW5ndWFnZSI6IiJ9fQ.xrdwMVnUOnP-sL6mOs9nN2mMNLzyvY9E6PEGpbXPRI8",
    # 正式环境
    "Authorization": "Bearer eyJhbGciOiJIUzI1NiJ9.eyJqdGkiOiJhZGFzZmFzZiIsInN1YiI6InRlc3RAdGVzdC5jb20iLCJpYXQiOjE3MzcyMDA0NTIsImV4cCI6MjM0MjAwMDQ1MiwiY29tbW9uSGVhZGVyUGFyYW1zIjp7InBsYXRmb3JtIjoiaW9zIiwiYXBwVmVyc2lvbiI6IjEuMC4wIiwibGFuZ3VhZ2UiOiJ6aC1DTiJ9fQ.a1S0EXaFNq0zmGzgclEKN-5fHDLj5rLX_WLwt7x7PFw",
}

# 并发测算数
num_calculations = 20  # 需要进行的测算次数
file_path = "test/1_3广发证券对账单.xlsx"  # 统一的文件路径

async def upload_file(session):
    data = aiohttp.FormData()
    data.add_field("brokerId", "1862880165273661441")
    data.add_field("file", open(file_path, 'rb'), filename=os.path.basename(file_path))

    try:
        async with session.post(upload_url, headers=upload_headers, data=data) as response:
            # 打印状态码和返回内容
            print(f"上传请求: {upload_url}")
            response_data = await response.json()
            print(f"上传请求resp_code: {response_data['code']}")

            
            # 检查返回的数据结构
            if "data" in response_data and isinstance(response_data["data"], list) and len(response_data["data"]) > 0:
                return response_data["data"][0].get("caculateion", {}).get("id")  # 获取返回的 caculateId
            else:
                print(f"返回的数据结构不符合预期: {response_data}")
                return None
    except Exception as e:
        print(f"上传文件时发生错误: {e}")
        return None

async def start_calculation(session, caculate_id):
    calculate_url = calculate_url_template.format(caculate_id)
    async with session.get(calculate_url, headers=upload_headers) as response:
        print(f"开始测算请求：{calculate_url}")
        result = await response.json()
        print(f"测算请求resp: {result}")
        print(f"测算结果 for caculateId {caculate_id}: {result}")

async def main():
    async with aiohttp.ClientSession() as session:
        # 上传文件并获取 caculateId
        tasks = [upload_file(session) for _ in range(num_calculations)]
        caculate_ids = await asyncio.gather(*tasks)

        for caculate_id in caculate_ids:
            if caculate_id:
                print(f"上传返回的 caculateId: {caculate_id}")
                # 开始测算
                await start_calculation(session, caculate_id)
            else:
                print("上传失败，未返回 caculateId")

if __name__ == "__main__":
    asyncio.run(main())


    """
    # 计算数据库测算耗时
    SELECT 
    DATE_FORMAT(FROM_UNIXTIME(created_at), '%Y-%m-%d %H:%i:%s') AS created_at_formatted,
    DATE_FORMAT(FROM_UNIXTIME(begin_time), '%Y-%m-%d %H:%i:%s') AS begin_time_formatted,
    DATE_FORMAT(FROM_UNIXTIME(end_time), '%Y-%m-%d %H:%i:%s') AS end_time_formatted,
    DATE_FORMAT(FROM_UNIXTIME(updated_at), '%Y-%m-%d %H:%i:%s') AS updated_at_formatted,
    TIMESTAMPDIFF(SECOND, FROM_UNIXTIME(created_at), FROM_UNIXTIME(updated_at)) AS seconds_diff
FROM 
    stock_loss_caculation where uid = '892969875830476800'
    """